package com.feng.rabbitmq.controller;

import com.feng.rabbitmq.config.DelayedQueueConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 发送延迟消息
 */
@Slf4j
@RestController
@RequestMapping("ttl")
public class SendMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //开始发送消息
    //http://localhost:8080/ttl/sendMsg/hhh
    @GetMapping("/sendMsg/{message}")
    public void sendMsg(@PathVariable("message")String message){
        log.info("当前时间：{}，发送一条信息给两个ttl队列：{}",new Date().toString(),message);

        rabbitTemplate.convertAndSend("X","XA","消息来自ttl为10s的队列： "+message);
        rabbitTemplate.convertAndSend("X","XB","消息来自ttl为40s的队列： "+message);
        //下面的这个是查找这个错误的语句：https://blog.csdn.net/qq_43987149/article/details/121893465
//        System.out.println("--------------------controller发送信息成功---------------------");
    }

    //http://localhost:8080/ttl/sendExpirationMsg/Hello,%20%E9%9D%99%E6%80%81%E7%9A%841/20000
    @GetMapping("/sendExpirationMsg/{message}/{ttlTime}")
    public void sendMsg(@PathVariable("message")String message,
                        @PathVariable("ttlTime")String ttltime){
        log.info("当前时间：{}，发送一条延迟了{}ms的信息给ttl队列：{}",new Date().toString(),ttltime,message);
        rabbitTemplate.convertAndSend("X","XC",message,message1 -> {
            message1.getMessageProperties().setExpiration(ttltime);
            return message1;
        });

    }

    /**
     * //2021-12-13 16:16:32.161  WARN 2408 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver :
     * // Resolved [org.springframework.web.bind.MissingPathVariableException:
     * // Required URI template variable 'ttlTime' for method parameter type
     * // Integer is not present]
     */
    //http://localhost:8080/ttl/sendDelayMsg/今天天气真好1/20000
    //http://localhost:8080/ttl/sendDelayMsg/今天天气真好2/2000
    @GetMapping("/sendDelayMsg/{message}/{delayTime}")
    public void sendMsg(@PathVariable("message")String message,
//                        @PathVariable("ttlTime")Integer delayTime) {
                        @PathVariable("delayTime")Integer delayTime) {
        log.info("当前时间：{}，发送一条延迟了{}ms的信息给delayed队列：{}", new Date().toString(), delayTime, message);
        rabbitTemplate.convertAndSend(DelayedQueueConfig.DELAYED_EXCHANGE_NAME,DelayedQueueConfig.DELAYED_ROUTING_KEY,message,message1 -> {
            message1.getMessageProperties().setDelay(delayTime);
            return message1;
        });
    }
}
